import os
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render
from ..forms import UpForm, UpModelForm
from .. import models

def upload_list(request):
    if request.method == "GET":
        return render(request, "app_02/upload_list.html")
    # # 'username': ['1321']
    # print(request.POST)     # 请求体中的数据
    # # {'avatar': [ < InMemoryUploadedFile: 微信图片_20250516212940.jpg(image / jpeg) >]}
    # print(request.FILES)    # 请求发过来的文件

    file_object = request.FILES.get("avatar")
    print(file_object)      # 微信图片_20250516212940.jpg

    f = open(file_object.name, mode="wb")
    for chunk in file_object.chunks():
        f.write(chunk)
    f.close()
    return HttpResponse("...")


def upload_form(request):
    title = "Form上传"
    if request.method == "GET":
        form = UpForm()
        return render(request, "app_02/upload_form.html", {"form": form, "title": title})

    form = UpForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # print(form.cleaned_data)
        # {'name': '糖果姐', 'age': 21, 'img': < InMemoryUploadedFile: 1.jpg(image / jpeg) >}
        # 1. 读取到图片内容，写入到文件夹中并获取文件的路径
        image_object = form.cleaned_data.get("img")

        # file_path = "app_02/image/{}.format(image_object.name)"
        # 直接与app_02平级
        # db_file_path = os.path.join("static", "app_02", "image", image_object.name)

        # media_path = os.path.join(settings.MEDIA_ROOT, "image", image_object.name)
        media_path = os.path.join("media", "image", image_object.name)
        f = open(media_path, mode="wb")
        for chunk in image_object.chunks():
            f.write(chunk)
        f.close()

        # 2. 将图片文件路径写入到数据库
        models.Boss.objects.create(
            name=form.cleaned_data["name"],
            age=form.cleaned_data["age"],
            img=media_path
        )

        return HttpResponse("上传成功")

    return render(request, "app_02/upload_form.html", {"form": form, "title": title})


def upload_modelform(request):
    """ 上传modelform """
    title = "ModelForm上传"
    if request.method == "GET":
        form = UpModelForm()
        return render(request, "app_02/upload_form.html", {"form": form, "title": title})

    form = UpModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 对于文件：自动保存
        form.save()
        return HttpResponse("成功")

    return render(request, "app_02/upload_form.html", {"form": form, "title": title})

